package com.eastcode.mobile.client.action;

import java.util.Iterator;
import java.util.Map;

import com.eastcode.base.action.BaseAction;
import com.eastcode.base.util.DateUtil;
import com.eastcode.base.util.GZipUtil;
import com.eastcode.base.util.HttpUtil;
import com.eastcode.mobile.client.service.ReceiveService;
import com.eastcode.mobile.server.user.entity.Location;
import com.eastcode.mobile.server.user.entity.Sms;
import com.eastcode.mobile.server.util.ServerLocator;
import com.google.appengine.repackaged.org.json.JSONObject;

public class OnReceivAction extends BaseAction {

	private static final long serialVersionUID = 1093903102967232262L;

	private ReceiveService receiveService = ServerLocator.getReceiveService();

	@Override
	protected void execute() {
		prepare(this);
	}

	public void location() {
		Location location = new Location();

		Map<String, String> paramMap = HttpUtil.parseRequest(request);
		Iterator<String> iterator = paramMap.keySet().iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			String param = request.getParameter(key);
			if (key.equals("USER_ID")) {
				location.setUserId(param);
			} else if (key.equals("LOCATION")) {
				try {
					JSONObject jsonObject = new JSONObject(param);
					String time = jsonObject.getString("time");
					String error = jsonObject.getString("error");
					String x = jsonObject.getString("x");
					String y = jsonObject.getString("y");
					String radius = jsonObject.getString("radius");
					String detail = jsonObject.getString("detail");
					location.setTime(DateUtil.parseDateTimeC(time));
					location.setError(error);
					location.setX(x);
					location.setX(y);
					location.setRadius(radius);
					location.setDetail(detail);
					System.out.println(key + "=======" + param);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
		// 位置
		receiveService.save(location);
	}

	public void smsReceive() {
		Sms sms = new Sms();

		Map<String, String> paramMap = HttpUtil.parseRequest(request);
		Iterator<String> iterator = paramMap.keySet().iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			String param = request.getParameter(key);

			if (key.equals("USER_ID")) {
				sms.setUserId(param);
			} else if (key.equals("MESSAGE")) {
				sms.setMessage(GZipUtil.uncompress(param));
			} else if (key.equals("senderNumber")) {
				sms.setSenderNumber(param);
			} else if (key.equals("sender")) {
				sms.setSender(param);
			} else if (key.equals("createTime")) {
				sms.setCreateTime(DateUtil.parseDateTime(param));
			}

			// 收信
			sms.setType("1");
		}

		// 保存短信
		receiveService.save(sms);

	}
}
